// pages/greeting-card/greeting-card.js
var util = require("../../utils/util.js");
const innerAudioContext = wx.createInnerAudioContext();
const recorderManager = wx.getRecorderManager();
var init;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        showPostType: !1,
        cardpic: '',
        blessing: '',
        audioDuration: 0,
        showTime1: '00:00',
        showTime2: '00:00',
        audioTime: 0,
        audioSeek: 0,
        showStart: !0,
        time: '00:00', //录音时长
        duration: 20000, //录音最大值ms 600000/20S
        playStatus: 0, //录音播放状态 0:未播放 1:正在播放
        speckPath: '', //后端保存的录音路径
        audiosrc: '',
        // audiosrc: 'http://img02.tuke88.com/newpreview_music/09/00/27/5c8912c300c9227199.mp3',
        origin: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        const _this = this;
        if (options.envelopUrl) {
            _this.setData({
                cardpic: options.envelopUrl
            })
        }
        if (options.origin) {
            _this.setData({
                origin: options.origin
            })
        }
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.record']) {
                    console.log('已授权');
                } else {
                    wx.authorize({
                        scope: 'scope.record',
                        success() {
                            console.log('开启授权');
                        }
                    })
                }
            }
        })
    },

    recordStart: function() {
        const _this = this;
        clearInterval(init);
        recorderManager.onStart((res) => {})
        recorderManager.onStop((res) => {
            console.log(res.tempFilePath);
            _this.setData({
                audiosrc: res.tempFilePath,
                showStart: !1
            })
            _this.recordingTimer(_this.data.time)
        })
        const options = {
            duration: this.data.duration, //指定录音的时长，单位 ms
            sampleRate: 16000, //采样率
            numberOfChannels: 1, //录音通道数
            encodeBitRate: 96000, //编码码率
            format: 'mp3', //音频格式，有效值 aac/mp3
            frameSize: 50, //指定帧大小，单位 KB
        }
        _this.recordingTimer();
        recorderManager.start(options);
    },

    recordTerm: function() {
        const _this = this;

        recorderManager.onStop((res) => {
            _this.setData({
                audiosrc: res.tempFilePath,
                showStart: !1,
                // showTime2: _this.data.time
            })
        })
        this.recordingTimer(_this.data.time)
        recorderManager.stop()
    },
    //删除录音
    delAudio: function() {
        const _this = this;
        wx.showModal({
            title: '重新录音',
            content: '是否重新录制?',
            success(res) {
                if (res.confirm) {
                    _this.setData({
                        time: 0, //录音时长
                        audiosrc: "", //音频路径
                        playStatus: 0,
                        showStart: !0
                    })
                }
            }

        })
    },

    //录音计时器
    recordingTimer: function(time) {
        var _this = this
        var count = 0
        if (time == undefined) {
            //将计时器赋值给init
            init = setInterval(function() {
                console.log(_this.data.time);
                count = count + 1;
                if (count < 10) {
                    time = '00:0' + count
                } else {
                    time = '00:' + count
                }
                _this.setData({
                    time: time
                })
            }, 1000);
        } else {
            clearInterval(init);
            console.log("暂停计时");
        }
    },

    showType: function() {
        const _this = this;
        util.request(getApp().api.user.isLogin).then(
            function(res) {
                if (res.code == 200) {
                    if (_this.data.blessing == '' && _this.data.showStart) {
                        wx.showToast({
                            title: '请选择文字祝福或语音祝福吧',
                            icon: "none"
                        });
                    } else if (_this.data.audiosrc) {
                        util.request(getApp().api.greeting.recordUpload, { file: _this.data.audiosrc }, 'POST').then(
                            function(res) {
                                if (res.code == 200) {
                                    console.log('录音上传完成');
                                    _this.setData({
                                        showPostType: !0,
                                        speckPath: res.speckPath
                                    })
                                } else {
                                    wx.showToast({
                                        title: res.msg, //提示的内容,
                                        icon: "none", //图标,
                                        mask: false, //显示透明蒙层，防止触摸穿透,
                                    });
                                    setTimeout(function() {
                                        wx.hideToast();
                                    }, 1500);
                                    return
                                }
                            }
                        );
                    } else {
                        _this.setData({
                            showPostType: !0
                        })
                    }
                } else {
                    wx.showToast({
                        title: res.msg, //提示的内容,
                        icon: "none", //图标,
                        //duration: 1500, //延迟时间,
                        mask: false, //显示透明蒙层，防止触摸穿透,
                    });
                    setTimeout(function() {
                        wx.hideToast();
                    }, 1500);
                    return
                }
            }
        );
    },
    toCancel: function() {
        this.setData({
            showPostType: !1
        })
    },
    nextStep: function(e) {
        const _this = this;
        const giveType = e.currentTarget.dataset.type;
        if (_this.data.origin == 'littleThought') {
            wx.setStorageSync("littleThought", JSON.stringify({
                type: giveType, //赠送方式
                blessing: _this.data.blessing, //文字祝福
                speckPath: _this.data.speckPath, //语音祝福
            }));
            wx.navigateTo({
                url: '/pages/gift-goods-list/gift-goods-list?origin=' + 'littleThought'
            })
        } else {
            wx.navigateTo({
                url: '/pages/give-order/give-order?type=' + giveType + '&blessing=' + _this.data.blessing + '&speckPath=' + _this.data.speckPath
            })
        }

    },
    bindkeyinput: function(e) {
        var t = '{"' + e.currentTarget.dataset.name + '":"' + e.detail.value + '"}';
        this.setData({
            blessing: e.detail.value
        })
    },
    //初始化播放器，获取duration
    Initialization() {
        var t = this;
        if (this.data.audiosrc.length != 0) {
            //设置src
            innerAudioContext.src = this.data.audiosrc;
            //运行一次
            innerAudioContext.play();
            innerAudioContext.pause();
            innerAudioContext.onCanplay(() => {
                //初始化duration
                innerAudioContext.duration
                setTimeout(function() {
                    //延时获取音频真正的duration
                    var duration = innerAudioContext.duration;
                    var min = parseInt(duration / 60);
                    var sec = parseInt(duration % 60);
                    if (min.toString().length == 1) {
                        min = `0${min}`;
                    }
                    if (sec.toString().length == 1) {
                        sec = `0${sec}`;
                    }
                    t.setData({ audioDuration: innerAudioContext.duration, showTime2: `${min}:${sec}` });
                }, 1000)
            })
        }
    },
    //拖动进度条事件
    sliderChange(e) {
        innerAudioContext.src = this.data.audiosrc;
        //获取进度条百分比
        var value = e.detail.value;
        this.setData({ audioTime: value });
        var duration = this.data.audioDuration;
        //根据进度条百分比及歌曲总时间，计算拖动位置的时间
        value = parseInt(value * duration / 100);
        //更改状态
        this.setData({ audioSeek: value, playStatus: true });
        //调用seek方法跳转歌曲时间
        innerAudioContext.seek(value);
        //播放歌曲
        innerAudioContext.play();
    },
    //播放、暂停按钮
    playAudio() {
        //获取播放状态和当前播放时间
        var playStatus = this.data.playStatus;
        var seek = this.data.audioSeek;
        innerAudioContext.pause();

        //  // 音频地址
        //     innerAudioContext.src = _this.data.audiosrc
        //         //在ios下静音时播放没有声音，默认为true，改为false就好了。
        innerAudioContext.obeyMuteSwitch = false

        //更改播放状态
        this.setData({ playStatus: !playStatus })
        if (playStatus) {
            //如果在播放则记录播放的时间seek，暂停
            this.setData({ audioSeek: innerAudioContext.currentTime });
        } else {
            //如果在暂停，获取播放时间并继续播放
            innerAudioContext.src = this.data.audiosrc;
            if (innerAudioContext.duration != 0) {
                this.setData({ audioDuration: innerAudioContext.duration });
            }
            //跳转到指定时间播放
            innerAudioContext.seek(seek);
            innerAudioContext.play();
        }
    },
    loadaudio() {
        var that = this;
        //设置一个计步器
        this.data.durationIntval = setInterval(function() {
            //当歌曲在播放时执行
            if (that.data.playStatus == true) {
                //获取歌曲的播放时间，进度百分比
                var seek = that.data.audioSeek;
                var duration = innerAudioContext.duration;
                var time = that.data.audioTime;
                time = parseInt(100 * seek / duration);
                //当歌曲在播放时，每隔一秒歌曲播放时间+1，并计算分钟数与秒数
                var min = parseInt((seek + 1) / 60);
                var sec = parseInt(seek % 60);
                //填充字符串，使3:1这种呈现出 03：01 的样式
                if (min.toString().length == 1) {
                    min = `0${min}`;
                }
                if (sec.toString().length == 1) {
                    sec = `0${sec}`;
                }
                var min1 = parseInt(duration / 60);
                var sec1 = parseInt(duration % 60);
                if (min1.toString().length == 1) {
                    min1 = `0${min1}`;
                }
                if (sec1.toString().length == 1) {
                    sec1 = `0${sec1}`;
                }
                //当进度条完成，停止播放，并重设播放时间和进度条
                if (time >= 100) {
                    innerAudioContext.stop();
                    that.setData({ audioSeek: 0, audioTime: 0, audioDuration: duration, playStatus: false, showTime1: `00:00` });
                    return false;
                }
                //正常播放，更改进度信息，更改播放时间信息
                that.setData({ audioSeek: seek + 1, audioTime: time, audioDuration: duration, showTime1: `${min}:${sec}`, showTime2: `${min1}:${sec1}` });
            }
        }, 1000);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.Initialization();
        this.loadaudio();
        this.setData({
            showPostType: !1
        })
    },
})